<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '添加')"
          >添加
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @cell-mouse-enter="(m) => m.active=true"
          @cell-mouse-leave="(m) => m.active=false"
          @sort-change="handleSort"
        >
          <el-table-column align="center" width="100" prop="id" label="用户ID" sortable="custom" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="realname" label="真名" width="180">
            <template slot-scope="scope">
              {{ scope.row.first_name }} {{ scope.row.last_name }}
            </template>
          </el-table-column>
          <el-table-column prop="tag" label="分组标签" width="180">
            <template slot-scope="scope">
              <el-tag
                v-for="tag in scope.row.tag"
                :key="tag"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="phone" label="电话" width="180" />
          <el-table-column prop="create_at" label="创建时间" width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.create_at }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="warning" @click="handleAction('password', scope.row)">设置密码</el-button>
              <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <template v-if="action === 'delete'">
        <el-form :model="temp">
          <el-form-item label="选择接收数据的员工" required>
            <el-select v-model="replace_user_id" placeholder="请选择接收数据的员工">
              <el-option
                v-for="item in data.filter(i => i.id !== temp.id)"
                :key="item.id"
                :label="item.first_name + item.last_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <el-form ref="dataForm" :model="temp" :rules="rules" label-position="left" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" :disabled="action !=='create'" placeholder="请输入手机号作为用户名" />
          <span style="color: #909399; font-size: 12px;">用户名必须是11位手机号</span>
        </el-form-item>
        <el-form-item v-if="action==='password' || action === 'create'" label="密码" prop="name">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="姓" prop="contact_name">
          <el-input v-model="temp.first_name" />
        </el-form-item>
        <el-form-item label="名" prop="contact_phone">
          <el-input v-model="temp.last_name" />
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-tag
            v-for="tag in temp.tag"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-autocomplete
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            :fetch-suggestions="querySearch"
            placeholder="输入标签,回车确认"
            size="small"
            style="width: 200px;"
            @select="handleAddTag"
            @keyup.enter.native="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
        </el-form-item>
        <el-form-item label="phone" prop="wechat">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
      </el-form>
      <el-alert>
        <template slot="title">
          <span>系统已经存在用户tag</span>
        </template>
        <el-tag v-for="tag in tags" :key="tag">
          {{ tag }}
        </el-tag>
      </el-alert>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { CRMGetProjectUsers, AddProjectUser, ModifyProjectUser } from '@/api/crm/crmmanage'
import qs from 'qs'
import { countries, customer_source, getCountryLabel } from '../../api/crm/crmcommon'
import { DeleteProjectUser } from '../../api/crm/crmmanage'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmcustomer',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('用户名必须是11位手机号'))
      } else {
        callback()
      }
    }

    return {
      data: [],
      listLoading: false,
      getCountryLabel: getCountryLabel,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      countries: countries,
      customer_sources: customer_source,
      action: null,
      dialogVisible: false,
      title: '',
      inputVisible: false,
      inputValue: '',
      tags: [],
      replace_user_id: null,
      temp: {
        username: '', // 用户名(手机号)
        first_name: '', // 姓
        last_name: '', // 名
        phone: '', // 联系电话
        password: '', // 密码
        tag: [],
        email: ''
      },
      // 表单验证规则
      rules: {
        username: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ]
      },
      width: '',
      innerDialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    querySearch(queryString, cb) {
      // 直接生成value数组表
      const results = this.tags.map(tag => ({ value: tag }))
      cb(results)
    },
    handleAddTag(item) {
      console.log(item)
      if (!this.temp.tag.includes(item.value)) {
        this.temp.tag.push(item.value)
        this.inputValue = ''
      }
    },
    handleClose(tag) {
      this.temp.tag.splice(this.temp.tag.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.tag.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    resetTemp() {
      this.temp = {
        username: '', // 供应商名称
        tag: [],
        first_name: '', // 企业类型
        last_name: '', // 地址
        phone: '', // 联系人名称
        password: '', // 联系电话
        email: ''
      }
    },
    getList() {
      this.listLoading = true
      CRMGetProjectUsers(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.tags = response.data.tags
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '添加新员工'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'password':
          this.width = '50%'
          this.title = '设置密码'
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除员工:${row.username}?`
          this.temp = Object.assign({}, row)
          // 去掉 password 字段
          delete this.temp.password
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改员工:${row.username}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.projectuser_id = row.projectuser_id
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp

      // 对于创建和编辑操作,先验证表单
      if (this.action === 'create' || this.action === 'edit') {
        this.$refs.dataForm.validate((valid) => {
          if (!valid) {
            this.$notify({
              title: '验证失败',
              message: '请检查表单信息',
              type: 'error',
              duration: 2000
            })
            return false
          }
          // 验证通过,执行对应操作
          this.executeAction(_data)
        })
      } else {
        // 删除和修改密码操作不需要表单验证
        this.executeAction(_data)
      }
    },
    executeAction(_data) {
      switch (this.action) {
        case 'create':
          // 验证数据是否为空
          if (!_data.username || !_data.first_name || !_data.last_name || !_data.phone || !_data.email) {
            this.$notify({
              title: '失败',
              message: '请填写完整信息',
              type: 'error',
              duration: 2000
            })
            return
          }
          AddProjectUser(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          DeleteProjectUser(_data.projectuser_id, { replace_user_id: this.replace_user_id }).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          ModifyProjectUser(_data.projectuser_id, _data).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
          break
        case
          'password':
          ModifyProjectUser(_data.projectuser_id, _data).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          })
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
